package com.example.wangzh.mytest;

import android.graphics.Matrix;
import android.os.Build;
import android.util.Log;
import android.view.View;

import androidx.annotation.RequiresApi;

import com.example.wangzh.mytest.base.BaseActivity;
import com.example.wangzh.mytest.databinding.ActivityTransformandmatrixTest2Binding;

public class TransformAndMatrixTest2Activity extends BaseActivity<ActivityTransformandmatrixTest2Binding> {
    public static final String TAG = TransformAndMatrixTest2Activity.class.getSimpleName();
    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void initView() {
        // 确保视图已经完成布局
        mBinding.testView.post(() -> {
            logCurrentState("初始状态");
        });
        setupClickListeners();
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void setupClickListeners() {
        mBinding.btnTest1.setOnClickListener(v -> testScaleThenMatrix());
        mBinding.btnTest2.setOnClickListener(v -> testMatrixThenScale());
        mBinding.btnTest3.setOnClickListener(v -> testMixedTransform());
        mBinding.btnReset.setOnClickListener(v -> resetView());
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void testScaleThenMatrix() {
        resetView();
        StringBuilder result = new StringBuilder();
        result.append("=== 测试1: 先setScale后setAnimationMatrix ===\n\n");

//         第一步：设置缩放
        result.append("第一步: setScale(2.0f, 1.5f)\n");
        mBinding.testView.setScaleX(2.0f);
        mBinding.testView.setScaleY(1.5f);
        logViewState(result, "setScale后");

        // 第二步：设置动画矩阵（包含平移）
        result.append("\n第二步: setAnimationMatrix(包含平移的矩阵)\n");
        Matrix matrix = new Matrix();
        matrix.postTranslate(50f, 30f); // 平移50px, 30px
        matrix.postScale(0.8f, 0.8f);   // 缩放0.8倍
        mBinding.testView.setAnimationMatrix(matrix);
        logViewState(result, "setAnimationMatrix后");

        result.append("\n关键发现:\n");
        result.append("- setAnimationMatrix会覆盖之前的scale变换\n");
        result.append("- 但scale属性值保持不变\n");
        result.append("- 实际视觉效果由animationMatrix决定\n");

        mBinding.tvResult.setText(result.toString());
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void testMatrixThenScale() {
        resetView();
        StringBuilder result = new StringBuilder();
        result.append("=== 测试2: 先setAnimationMatrix后setScale ===\n\n");

        // 第一步：设置动画矩阵
        result.append("第一步: setAnimationMatrix(初始矩阵)\n");
        Matrix matrix = new Matrix();
        matrix.postTranslate(100f, 50f);
        matrix.postScale(1.2f, 1.2f);
        mBinding.testView.setAnimationMatrix(matrix);
        logViewState(result, "setAnimationMatrix后");

        // 第二步：设置缩放
        result.append("\n第二步: setScale(0.5f, 0.5f)\n");
        mBinding.testView.setScaleX(0.5f);
        mBinding.testView.setScaleY(0.5f);
        logViewState(result, "setScale后");

        result.append("\n关键发现:\n");
        result.append("- setScale不会影响animationMatrix\n");
        result.append("- 但最终的视觉效果是两者的叠加\n");
        result.append("- View的变换 = animationMatrix × scale变换\n");

        mBinding.tvResult.setText(result.toString());
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void testMixedTransform() {
        resetView();
        StringBuilder result = new StringBuilder();
        result.append("=== 测试3: 混合变换测试 ===\n\n");

        result.append("初始状态:\n");
        logViewState(result, "初始");

        // 复杂变换序列
        result.append("\n1. setScale(2.0f, 2.0f)\n");
        mBinding.testView.setScaleX(2.0f);
        mBinding.testView.setScaleY(2.0f);
        logViewState(result, "setScale后");

        result.append("\n2. setAnimationMatrix(平移(80f,40f)+旋转45)\n");
        Matrix matrix1 = new Matrix();
        matrix1.postTranslate(80f, 40f);
        matrix1.postRotate(45); // 旋转45度
        mBinding.testView.setAnimationMatrix(matrix1);
        logViewState(result, "setAnimationMatrix后");

        result.append("\n3. 再次setScale(0.5f, 0.5f)\n");
        mBinding.testView.setScaleX(0.5f);
        mBinding.testView.setScaleY(0.5f);
        logViewState(result, "再次setScale后");

        result.append("\n4. 设置新的animationMatrix\n");
        Matrix matrix2 = new Matrix();
        matrix2.postScale(1.5f, 1.5f);
        matrix2.postTranslate(-20f, -10f);
        mBinding.testView.setAnimationMatrix(matrix2);
        logViewState(result, "新animationMatrix后");

        // 分析最终矩阵
        analyzeFinalMatrix(result);

        mBinding.tvResult.setText(result.toString());
    }

    private void analyzeFinalMatrix(StringBuilder result) {
        result.append("变换顺序分析:\n");
        result.append("1. 先应用scale属性变换 (").append(mBinding.testView.getScaleX()).append(", ").append(mBinding.testView.getScaleY()).append(")\n");
        result.append("2. 再应用animationMatrix变换\n");
        result.append("3. 最终矩阵 = animationMatrix × scaleMatrix\n");
    }

    private void logViewState(StringBuilder result, String step) {
        result.append(step).append(":\n");
        result.append("  ScaleX: ").append(mBinding.testView.getScaleX()).append("\n");
        result.append("  ScaleY: ").append(mBinding.testView.getScaleY()).append("\n");
        result.append("  TranslationX: ").append(mBinding.testView.getTranslationX()).append("\n");
        result.append("  TranslationY: ").append(mBinding.testView.getTranslationY()).append("\n");

        // 获取当前矩阵
        float[] matrixValues = new float[9];
        mBinding.testView.getMatrix().getValues(matrixValues);
        result.append("  当前矩阵: ").append(formatMatrixValues(matrixValues)).append("\n");

        // 获取animationMatrix（如果存在）
        try {
            Matrix animMatrix = getAnimationMatrix(mBinding.testView);
            if (animMatrix != null) {
                float[] animValues = new float[9];
                animMatrix.getValues(animValues);
                result.append("  AnimationMatrix: ").append(formatMatrixValues(animValues)).append("\n");
            }
        } catch (Exception e) {
            result.append("  AnimationMatrix: 无法获取\n");
        }

        // 记录布局信息
        result.append("  布局位置(getLeft等): [").append(mBinding.testView.getLeft()).append(", ")
                .append(mBinding.testView.getTop()).append(", ").append(mBinding.testView.getRight())
                .append(", ").append(mBinding.testView.getBottom()).append("]\n");
        result.append("  实际位置(getX等): (").append(mBinding.testView.getX()).append(", ")
                .append(mBinding.testView.getY()).append(")\n");
    }

    private void logCurrentState(String title) {
        Log.d(TAG, title + ":");
        Log.d(TAG, "ScaleX: " + mBinding.testView.getScaleX() + ", ScaleY: " + mBinding.testView.getScaleY());
        Log.d(TAG, "TranslationX: " + mBinding.testView.getTranslationX() + ", TranslationY: " + mBinding.testView.getTranslationY());

        float[] matrixValues = new float[9];
        mBinding.testView.getMatrix().getValues(matrixValues);
        Log.d(TAG, "Matrix: " + java.util.Arrays.toString(matrixValues));
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void resetView() {
        mBinding.testView.setScaleX(1.0f);
        mBinding.testView.setScaleY(1.0f);
        mBinding.testView.setTranslationX(0f);
        mBinding.testView.setTranslationY(0f);
        mBinding.testView.setRotation(0f);
        mBinding.testView.setAnimationMatrix(null);
        mBinding.testView.invalidate();
    }

    // 工具方法：格式化矩阵值显示
    private String formatMatrixValues(float[] values) {
        return String.format("[%.2f, %.2f, %.2f]\n              [%.2f, %.2f, %.2f]\n              [%.2f, %.2f, %.2f]",
                values[0], values[1], values[2],
                values[3], values[4], values[5],
                values[6], values[7], values[8]);
    }

    private String formatMatrix(Matrix matrix) {
        float[] values = new float[9];
        matrix.getValues(values);
        return formatMatrixValues(values);
    }

    private float[] getMatrixValues(Matrix matrix) {
        float[] values = new float[9];
        matrix.getValues(values);
        return values;
    }

    // 通过反射获取animationMatrix（仅用于测试）
    private Matrix getAnimationMatrix(View view) {
        try {
            java.lang.reflect.Field field = View.class.getDeclaredField("mRenderNode");
            field.setAccessible(true);
            Object renderNode = field.get(view);

            java.lang.reflect.Method method = renderNode.getClass().getMethod("getAnimationMatrix");
            return (Matrix) method.invoke(renderNode);
        } catch (Exception e) {
            return null;
        }
    }
}
